﻿using JWT;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using WebApplication1.Auth.common;

namespace WebApplication1.Auth.CustomAuth
{
    public class ApiJWTAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var success = true;
            var authHeader = from t in actionContext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();
            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();
                success = success && !string.IsNullOrEmpty(token);
                if (success)
                {
                    try
                    {

                        token = token.Remove(0, 7);

                        //func委托可以写一些自定义验证逻辑-如权限控制
                        success =success&& TokenContext.Validate(token, payLoad =>
                        {
                            //验证其他playload内容
                            return true;
                        });

                        #region 注释部分
                        ////secret需要加密
                        //IJsonSerializer serializer = new JsonNetSerializer();
                        //IDateTimeProvider provider = new UtcDateTimeProvider();
                        //IJwtValidator validator = new JwtValidator(serializer, provider);
                        //IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        //IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                        //const string secret = "GQDstclechengroberbojPOXOYg5MbeJ1XT0uFiwDVvVBrk";


                        //var json = decoder.DecodeToObject<PlayLoad>(token, secret, verify: true);
                        //if (json != null)
                        //{
                        //    actionContext.RequestContext.RouteData.Values.Add("auth", json);
                        //    return true;
                        //}
                        //return false;

                        #endregion



                    }
                    catch (Exception ex)
                    {
                        success = false;
                    }
                }
            }
            return success;
        }
    }
}